<template>
  <div class="folder-tree-item" :style="{ paddingLeft: `${folder.level * 20}px` }">
    <div 
      class="folder-content" 
      :class="{ 'selected': isSelected }"
      @click="handleSelect"
    >
      <span 
        class="expand-icon" 
        :class="{ 'expanded': folder.expanded }"
        @click.stop="handleToggle"
      >
        <svg 
          viewBox="0 0 24 24" 
          width="16" 
          height="16"
          :style="{ opacity: hasChildren ? 1 : 0.3 }"
        >
          <path 
            d="M10 6L8.59 7.41 13.17 12l-4.58 4.59L10 18l6-6z" 
            fill="currentColor"
          />
        </svg>
      </span>
      <span class="folder-icon">
        <svg viewBox="0 0 24 24" width="20" height="20">
          <path 
            d="M10 4H4c-1.1 0-1.99.9-1.99 2L2 18c0 1.1.9 2 2 2h16c1.1 0 2-.9 2-2V8c0-1.1-.9-2-2-2h-8l-2-2z" 
            fill="currentColor"
          />
        </svg>
      </span>
      <span class="folder-name">{{ folder.name }}</span>
      
      <!-- 下拉菜单按钮 -->
      <span 
        class="folder-menu-icon" 
        @click.stop="toggleMenu"
        v-if="isAdmin || isAdvancedLibraryAdmin || isEditRole || isAssignRole"
      >
        <svg viewBox="0 0 24 24" width="16" height="16">
          <path 
            d="M12 8c1.1 0 2-.9 2-2s-.9-2-2-2-2 .9-2 2 .9 2 2 2zm0 2c-1.1 0-2 .9-2 2s.9 2 2 2 2-.9 2-2-.9-2-2-2zm0 6c-1.1 0-2 .9-2 2s.9 2 2 2 2-.9 2-2-.9-2-2-2z" 
            fill="currentColor"
          />
        </svg>
      </span>
      
      <!-- 下拉菜单 -->
      <div v-if="showMenu && (isAdmin || isAdvancedLibraryAdmin || isEditRole || isAssignRole)" class="folder-menu" @click.stop>
        <div class="menu-item" @click="showNewFolderDialog">
          <span>新建文件夹</span>
        </div>
        <div class="menu-item" @click="showUploadDialog">
          <span>上传文件</span>
        </div>
        <div class="menu-item" @click="showUploadDirectoryDialog">
          <span>上传文件夹</span>
        </div>
        <div class="menu-item" @click="startRenameFolder">
          <span>重命名</span>
        </div>
        <div class="menu-item delete" @click="confirmDeleteFolder">
          <span>删除文件夹</span>
        </div>
      </div>
      
      <!-- 重命名输入框 -->
      <div v-if="isRenaming" class="rename-input-container">
        <input
          ref="renameInput"
          v-model="renameValue"
          type="text"
          class="rename-input"
          @blur="saveRename"
          @keyup.enter="saveRename"
          @keyup.esc="cancelRename"
        />
      </div>
      
      <!-- 上传文件对话框 -->
      <UploadFileModal
        v-if="showUploadModal"
        :show="showUploadModal"
        @close="showUploadModal = false"
        @upload="handleUploadComplete"
      />

      <!-- 上传文件夹对话框 -->
      <UploadDirectoryModal
        v-if="showUploadDirectoryModal"
        :show="showUploadDirectoryModal"
        :folderId="props.folder.id"
        @close="showUploadDirectoryModal = false"
        @upload="handleDirectoryUploadComplete"
      />
    </div>
    
    <!-- 新建文件夹对话框 -->
    <div v-if="showNewFolderModal" class="modal-overlay" @click.self="showNewFolderModal = false">
      <div class="modal-content">
        <div class="modal-header">
          <h3>新建文件夹</h3>
          <button class="close-btn" @click="showNewFolderModal = false">&times;</button>
        </div>
        <div class="modal-body">
          <div class="form-group">
            <label for="folder-name">文件夹名称:</label>
            <input 
              type="text" 
              id="folder-name" 
              v-model="newFolderName" 
              class="input-field"
              placeholder="请输入文件夹名称"
            />
          </div>
        </div>
        <div class="modal-footer">
          <button class="cancel-btn" @click="showNewFolderModal = false">取消</button>
          <button class="submit-btn" @click="createNewFolder" :disabled="!newFolderName.trim()">
            创建
          </button>
        </div>
      </div>
    </div>
    
    <div v-if="folder.expanded" class="children">
      <FolderTreeItem
        v-for="child in folder.children"
        :key="child.id"
        :folder="child"
        @select="$emit('select', $event)"
        @toggle="$emit('toggle', $event)"
      />
    </div>
  </div>
</template>

<script setup lang="ts">
import { computed, ref, nextTick } from 'vue';
import { useKnowledgeBaseStore } from '../../stores/knowledgebaseStore';
import type { KnowledgeBase } from '../../stores/knowledgebaseStore';
import { ElMessageBox,ElMessage } from 'element-plus';
import UploadFileModal from './UploadFileModal.vue';
import UploadDirectoryModal from './UploadDirectoryModal.vue';
import { User } from '../../types';

const store = useKnowledgeBaseStore();

interface Props {
  folder: KnowledgeBase;
}

const props = defineProps<Props>();
const emit = defineEmits<{
  (e: 'select', folder: KnowledgeBase): void;
  (e: 'toggle', folder: KnowledgeBase): void;
  (e: 'update-folder', payload: { id: string; name: string }): void;
}>();

// 获取当前登录用户信息
const userInfoStr = localStorage.getItem('userInfo');
const currentUser = ref<User | null>(userInfoStr ? JSON.parse(userInfoStr) : null);
const isAdmin = computed(() => currentUser.value?.roleName === '超级管理员');
const isAdvancedLibraryAdmin = computed(() => {
  if (isAdmin.value) return false;
  if (!currentUser.value?.knowledgeBaseGroupRoleInfos) return false;
  return Object.entries(currentUser.value.knowledgeBaseGroupRoleInfos).some(
    ([groupId, roleId]) => groupId === store.selectedGroup?.id && roleId === 6
  );
});
const isEditRole = computed(() => {
  if (isAdmin.value || isAdvancedLibraryAdmin.value) return false;
  if (!currentUser.value?.knowledgeBaseGroupRoleInfos) return false;
  return Object.entries(currentUser.value.knowledgeBaseGroupRoleInfos).some(
    ([groupId, roleId]) => groupId === store.selectedGroup?.id && roleId === 7
  );
});
 const isAssignRole = computed(() => {
  if (isAdmin.value || isAdvancedLibraryAdmin.value) return false;
  if (!currentUser.value?.knowledgeBaseGroupRoleInfos) return false;
  return Object.entries(currentUser.value.knowledgeBaseGroupRoleInfos).some(
    ([groupId, roleId]) => groupId === store.selectedGroup?.id && roleId === 11
  );
 });
// 菜单状态
const showMenu = ref(false);
const showNewFolderModal = ref(false);
const showUploadModal = ref(false);
const showUploadDirectoryModal = ref(false);
const newFolderName = ref('');
const isRenaming = ref(false);
const renameValue = ref('');
const renameInput = ref<HTMLInputElement | null>(null);

const isSelected = computed(() => {
  return store.selectedFolder?.id === props.folder.id;
});

const hasChildren = computed(() => {
  // 如果已经有子文件夹，直接返回true
  if (props.folder.children.length > 0) {
    return true;
  }
  
  // 如果已经加载过该文件夹，但没有子文件夹，返回false
  if (store.loadedFolders.has(props.folder.id)) {
    return false;
  }
  
  // 如果还没有加载过该文件夹，默认显示展开图标
  // 但在点击展开时会加载子文件夹
  return true;
});

const handleSelect = () => {
  emit('select', props.folder);
  emit('toggle', props.folder); // 添加这一行，使点击文件夹名称时也触发展开/折叠
};

const handleToggle = () => {
  emit('toggle', props.folder);
};

// 切换菜单显示/隐藏
const toggleMenu = (e: Event) => {
  e.stopPropagation();
  showMenu.value = !showMenu.value;
  
  // 点击外部关闭菜单
  if (showMenu.value) {
    const closeMenu = () => {
      showMenu.value = false;
      document.removeEventListener('click', closeMenu);
    };
    setTimeout(() => {
      document.addEventListener('click', closeMenu);
    }, 0);
  }
};

// 显示新建文件夹对话框
const showNewFolderDialog = () => {
  showMenu.value = false;
  showNewFolderModal.value = true;
  newFolderName.value = '';
};

// 显示上传文件对话框
const showUploadDialog = () => {
  showMenu.value = false;
  showUploadModal.value = true;
};

// 显示上传文件夹对话框
const showUploadDirectoryDialog = () => {
  showMenu.value = false;
  showUploadDirectoryModal.value = true;
};

// 处理文件夹上传完成
const handleDirectoryUploadComplete = async (files: File[], relativePaths: string[]) => {
  try {
    if (!props.folder.id) return;
    
    const success = await store.uploadDirectory(props.folder.id, files, relativePaths);
    if (success) {
      showUploadDirectoryModal.value = false;
      
      // 如果当前文件夹是展开的，刷新其子文件夹
      if (props.folder.expanded) {
        await store.fetchKnowledgeBases(props.folder.id, true);
      }
      
      // 如果当前文件夹是选中的文件夹，刷新文件列表
      if (store.selectedFolder && store.selectedFolder.id === props.folder.id) {
        await store.selectFolder(props.folder);
      }
    }
  } catch (error) {
    console.error('处理文件夹上传失败:', error);
    ElMessage.error('文件夹上传失败');
  }
};

// 创建新文件夹
const createNewFolder = async () => {
  if (!newFolderName.value.trim()) return;
  
  try {
    if (!store.selectedGroup) {
      ElMessage.error('请先选择一个资料库');
      return;
    }
    
    const success = await store.createKnowledgeBase(newFolderName.value.trim(), props.folder.id, store.selectedGroup.id);
    if (success) {
      showNewFolderModal.value = false;
      newFolderName.value = '';
      
      // 如果当前文件夹是展开的，刷新其子文件夹
      if (props.folder.expanded) {
        await store.fetchKnowledgeBases(props.folder.id, true);
      }
    }
  } catch (error) {
    console.error('创建文件夹失败:', error);
  }
};

// 确认删除文件夹
const confirmDeleteFolder = () => {
  showMenu.value = false;
  
  ElMessageBox.confirm(
    `确定要删除文件夹 "${props.folder.name}" 吗？此操作将删除该文件夹及其所有内容，且不可恢复。`,
    '删除确认',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(() => {
    deleteFolder();
  }).catch(() => {
    // 用户取消删除
  });
};

// 删除文件夹
const deleteFolder = async () => {
  try {
    await store.deleteKnowledgeBase(props.folder.id);
  } catch (error) {
    console.error('删除文件夹失败:', error);
  }
};

// 开始重命名文件夹
const startRenameFolder = () => {
  renameValue.value = props.folder.name;
  isRenaming.value = true;
  showMenu.value = false;
  nextTick(() => {
    renameInput.value?.focus();
    renameInput.value?.select();
  });
};

// 保存重命名
const saveRename = async () => {
  if (!renameValue.value.trim() || renameValue.value === props.folder.name) {
    isRenaming.value = false;
    return;
  }

  try {
    if (!store.selectedGroup) {
      ElMessage.error('请先选择一个资料库');
      return;
    }
    const success = await store.updateKnowledgeBase(props.folder.id, {
      name: renameValue.value.trim(),
      fatherFolderId: props.folder.parentId,
      knowledgeBaseGroupId: store.selectedGroup.id
    });
    
    if (success) {
      emit('update-folder', {
        id: props.folder.id,
        name: renameValue.value.trim()
      });
      ElMessage.success('重命名成功');
    } else {
      ElMessage.error('重命名失败');
    }
  } catch (error) {
    console.error('重命名文件夹失败:', error);
    ElMessage.error('重命名失败');
  } finally {
    isRenaming.value = false;
  }
};

// 取消重命名
const cancelRename = () => {
  isRenaming.value = false;
};

// 处理文件上传完成 (单文件)
    const handleUploadComplete = async (file: File) => {
      try {
        if (!props.folder.id) return;
        
        const success = await store.uploadFile(props.folder.id, file);
    if (success) {
      showUploadModal.value = false;
      
      // 刷新文件夹内容
      if (props.folder.expanded) {
        await store.fetchKnowledgeBases(props.folder.id, true);
      }
      
      // 如果当前文件夹是选中的文件夹，刷新文件列表
      if (store.selectedFolder && store.selectedFolder.id === props.folder.id) {
        await store.selectFolder(props.folder);
      }
    }
  } catch (error) {
    console.error('处理上传完成失败:', error);
  }
};
</script>

<style scoped>
.folder-tree-item {
  font-size: 14px;
  position: relative;
}

.folder-content {
  display: flex;
  align-items: center;
  padding: 8px;
  cursor: pointer;
  border-radius: 4px;
  transition: background-color 0.2s;
}

.folder-content:hover {
  background-color: #f0f0f0;
}

.folder-content.selected {
  background-color: #e6f4ff;
  color: #1890ff;
}

.expand-icon {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 24px;
  height: 24px;
  transition: transform 0.2s;
  color: #666;
}

.expand-icon.expanded {
  transform: rotate(90deg);
}

.folder-icon {
  display: flex;
  align-items: center;
  margin-right: 8px;
  color: #666;
}

.selected .folder-icon {
  color: #1890ff;
}

.folder-name {
  flex: 1;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.folder-menu-icon {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 24px;
  height: 24px;
  color: #666;
  opacity: 0;
  transition: opacity 0.2s;
}

.folder-content:hover .folder-menu-icon {
  opacity: 1;
}

.folder-menu {
  position: absolute;
  right: 8px;
  top: 36px;
  width: 120px;
  background-color: white;
  border-radius: 4px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
  z-index: 10;
}

.menu-item {
  padding: 8px 12px;
  cursor: pointer;
  transition: background-color 0.2s;
}

.menu-item:hover {
  background-color: #f0f0f0;
}

.menu-item.delete:hover {
  background-color: #fff1f0;
  color: #ff4d4f;
}

.children {
  margin-top: 2px;
}

/* 模态框样式 */
.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 100;
}

.modal-content {
  background-color: white;
  border-radius: 4px;
  width: 400px;
  max-width: 90%;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

.modal-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px;
  border-bottom: 1px solid #f0f0f0;
}

.modal-header h3 {
  margin: 0;
  font-size: 16px;
  font-weight: 500;
}

.close-btn {
  background: none;
  border: none;
  font-size: 20px;
  cursor: pointer;
  color: #999;
}

.modal-body {
  padding: 16px;
}

.form-group {
  margin-bottom: 16px;
}

.form-group label {
  display: block;
  margin-bottom: 8px;
  font-weight: 500;
}

.input-field {
  width: 100%;
  padding: 8px 12px;
  border: 1px solid #d9d9d9;
  border-radius: 4px;
  font-size: 14px;
}

.input-field:focus {
  border-color: #1890ff;
  outline: none;
  box-shadow: 0 0 0 2px rgba(24, 144, 255, 0.2);
}

.modal-footer {
  padding: 16px;
  border-top: 1px solid #f0f0f0;
  display: flex;
  justify-content: flex-end;
  gap: 8px;
}

.cancel-btn, .submit-btn {
  padding: 8px 16px;
  border-radius: 4px;
  font-size: 14px;
  cursor: pointer;
}

.cancel-btn {
  background-color: white;
  border: 1px solid #d9d9d9;
}

.submit-btn {
  background-color: #1890ff;
  border: 1px solid #1890ff;
  color: white;
}

.submit-btn:disabled {
  background-color: #f5f5f5;
  border-color: #d9d9d9;
  color: #bfbfbf;
  cursor: not-allowed;
}

/* 重命名输入框样式 */
.rename-input-container {
  position: absolute;
  left: 40px;
  right: 40px;
  top: 0;
  height: 100%;
  display: flex;
  align-items: center;
  background-color: white;
  z-index: 5;
}

.rename-input {
  width: 100%;
  padding: 4px 8px;
  border: 1px solid #1890ff;
  border-radius: 4px;
  font-size: 14px;
  box-shadow: 0 0 0 2px rgba(24, 144, 255, 0.2);
}

.rename-input:focus {
  outline: none;
  border-color: #1890ff;
}
</style>